<script setup lang="ts">
import { ref, onMounted, toRaw } from "vue";
import ModeInfo from "./ModelInfo.vue";
import { getAppConfig, delModel, saveAppConfig } from "@/api/application";
import type { formTable } from "../utils/types";
import { addNewModel } from "@/api/application";
import { ElMessage } from "element-plus";
import { message } from "@/utils/message";
const ModelConfigs = ref([]);
const newModelConfig = ref();
const appLink = ref();
const appRef = ref();
const props = withDefaults(defineProps<formTable>(), {
  id: 0,
  appName: ""
});
defineExpose({ addModel, saveAppCon });
//const emit = defineEmits(["delModel"]);
//添加一个模型
async function addModel() {
  const Result = await addNewModel({ appID: props.id });
  if (Result.isSuccess) {
    //console.log(Result.result);
    ModelConfigs.value.push(toRaw(Result.result));
  } else {
    ElMessage(Result.msg);
  }
}

async function saveAppCon() {
  //对数据进行处理
  const Result = await saveAppConfig({
    appID: props.id,
    appModels: ModelConfigs.value,
    newModeConfig: [],
    hasModels: true
  });
  if (Result.isSuccess) {
    message("保存成功！");
  } else {
    message(Result.msg);
  }
}

onMounted(async () => {
  const Result = await getAppConfig({ appID: props.id });
  if (Result.isSuccess) {
    newModelConfig.value = Result.result.newModeConfig[0]
      .rolesList as ModelInfo;
    appLink.value = Result.result.appLink;
    if (Result.result.hasModels) {
      ModelConfigs.value = Result.result.appModels;
      //console.log(Result.result.appModels);
    } else {
      addModel();
    }
  } else {
    alert(Result.msg);
  }
});

//删除一个功能
const delModeFun = async id => {
  const Result = await delModel({ modelID: id });
  if (Result.isSuccess) {
    ModelConfigs.value = ModelConfigs.value.filter(item => {
      console.log(item.modaInfo.id);
      return item.modaInfo.id != id;
    });
    message("删除成功!");
  } else {
    message(Result.msg);
  }
};
</script>

<template>
  <ModeInfo
    :ref="appRef"
    :modaInfo="item.modaInfo"
    :roleConfig="item.roleConfig"
    :userRoel="newModelConfig"
    :appLink="appLink"
    v-for="item in ModelConfigs"
    :key="item"
    @delModel="delModeFun"
  />
</template>
